package com.bw.service;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.NumberUtil;
import com.bw.entity.AssetsInfo;
import com.bw.entity.Source;
import com.bw.entity.Type;
import com.bw.mapper.AssetsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import java.util.List;

@Service
public class AssetsServiceImpl implements AssetsService {

    @Autowired
    AssetsMapper assetsMapper;

    @Override
    public AssetsInfo add(AssetsInfo assetsInfo) {
//        (10)表单非空校验，“*”非空字段（5分）
//            if (assetsInfo.getName() == null || assetsInfo.getName() == ""){
//
//                    throw new RuntimeException("资产名称必填");
//
//            }

        // Assert 断言（断定 判定）断定 assetsInfo.getName() 不是空， 如果是空 则抛异常
        Assert.notBlank(assetsInfo.getName(), "资产名称必填");
        Assert.notNull(assetsInfo.getTypeId(), "资产类别必填");
        Assert.notNull(assetsInfo.getSourceId(), "资产来源必填");
        Assert.notBlank(assetsInfo.getCreateTime(), "购入时间必填");
        Assert.notBlank(assetsInfo.getPrice(), "购入价格必填");
        Assert.notBlank(assetsInfo.getNum(), "资产编号必填");


//        (11)资产编号唯一性校验， 不能重复（5分）
        AssetsInfo assetsInfoDB = assetsMapper.getByNum(assetsInfo.getNum());

        if (assetsInfoDB != null) {
            throw new RuntimeException("资产编号不能重复");
        }

//        (12)购入价格校验，必须为数值类型（5分）

        String price = assetsInfo.getPrice();

        boolean number = NumberUtil.isNumber(price); // 判断字符串是不是数值

        if (!number) {
            throw new RuntimeException("购入价格必须为数值");
        }


//        (13)控制打印方法参数（5分）
        System.out.println(assetsInfo);


//        (14)添加成功（5分）

        assetsMapper.add(assetsInfo);

        return assetsInfo;
    }

    @Override
    public AssetsInfo selectByNum(String num) {
        //查询回显数据
        AssetsInfo assetsInfo = assetsMapper.getByNum(num);

//        (16)该接口同时返回资产类型下拉框数据（5分）
        List<Type> typeList = assetsMapper.getTypeList();
        assetsInfo.setTypeList(typeList);

//        (17)该接口同时返回资产来源下拉框数据（5分）
        List<Source> sourceList = assetsMapper.getSourceList();
        assetsInfo.setSourceList(sourceList);
        return assetsInfo;
    }
}
